package com.shop.test;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import com.shop.dao.DeptMapper;
import com.shop.dao.EmpMapper;
import com.shop.entity.Dept;
import com.shop.util.MyBatisUtil;

public class MyBatisTest1 {
	
	@Test
	public void testMyBatis3() throws IOException{
		SqlSession openSession = MyBatisUtil.getSqlSession();
		try{
			EmpMapper mapper = openSession.getMapper(EmpMapper.class);
			//xxxExample就是封装查询条件的
			//1、查询所有
			//List<Employee> emps = mapper.selectByExample(null);
			//2、查询员工名字中有e字母的，和员工性别是1的
			//封装员工查询条件的example
			//EmployeeExample example = new EmployeeExample();
			//创建一个Criteria，这个Criteria就是拼装查询条件
			//select id, last_name, email, gender, d_id from tbl_employee 
			//WHERE ( last_name like ? and gender = ? ) or email like "%e%"
			//Criteria criteria = example.createCriteria();
/*			criteria.andLastNameLike("%e%");
			criteria.andGenderEqualTo("1");
			
			Criteria criteria2 = example.createCriteria();
			criteria2.andEmailLike("%e%");
			example.or(criteria2);
			
			List<Emp> list = mapper.selectByExample(example);
			for (Emp employee : list) {
				System.out.println(employee.getId());
			}
			*/
		}finally{
			openSession.close();
		}
	}
	@Test
	public void testSelectAll(){
		SqlSession session  =MyBatisUtil.getSqlSession();
		DeptMapper mapper = session.getMapper(DeptMapper.class);
		List<Dept> list = mapper.selectAll();
		for (Dept dept : list) {
			System.out.println(dept);
		}
		MyBatisUtil.closesSession(session);
	}
	
	
	
	//测试生成代码
	@Test
	public void testGenerator() throws Exception{
		List<String> warnings = new ArrayList<String>();
		   boolean overwrite = true;
		   File configFile = new File("generatorConfig.xml");
		   ConfigurationParser cp = new ConfigurationParser(warnings);
		   Configuration config = cp.parseConfiguration(configFile);
		   DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		   MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		   myBatisGenerator.generate(null);
	}
	
	
	@Test
	public void test1() throws IOException{
		String config = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(config);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = sessionFactory.openSession();
		System.out.println(session);
	}
}
